/* -----------------------------------------------------
 iCompose
 iComposeAppDelegate.m
 
 Created by Team: THE BEARD on 18/10/09
 Members who contributed to this file:
 1. Ethan Holmes
 
 Simon Fraser University, 2009.
 ----------------------------------------------------- */

#import "iComposeAppDelegate.h"
#import "iComposeViewController.h"

@implementation iComposeAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize staffArray;
@synthesize dataFilePath;

-(id)init {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex: 0];
	NSString *path = [documentsDirectory stringByAppendingPathComponent:@"staff.dat"];
	[self setDataFilePath: path];
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if([fileManager fileExistsAtPath:dataFilePath]) {
		NSLog(@"Data file found. Reading into memory.");
		NSMutableData *theData;
		NSKeyedUnarchiver *decoder;
		NSMutableArray *tempArray;
		
		theData = [NSData dataWithContentsOfFile: dataFilePath];
		decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData: theData];
		tempArray = [decoder decodeObjectForKey:@"staffArray"];
		[self setStaffArray: tempArray];
		[decoder finishDecoding];
		[decoder release];
	} else {
		NSLog(@"No file found, creating empty array.");
		staffArray = [[NSMutableArray alloc] init];
	}
	return self;
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// Splash screen
    sleep(0.5);
	
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

-(void)applicationWillTerminate:(UIApplication*)application {
	NSMutableData *theData;
	NSKeyedArchiver *encoder;
	
	theData = [NSMutableData data];
	encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData: theData];
	
	[encoder encodeObject: staffArray forKey:@"staffArray"];
	[encoder finishEncoding];
	
	[theData writeToFile: dataFilePath atomically:YES];
	[encoder release];
}

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}


@end
